import { login as apiLogin, register as apiRegister, logout as apiLogout, getUserInfo } from '../../api/user'

const state = {
  // 用户信息
  user: {
    id: null,
    username: '',
    userType: 'user', // 'user' 或 'admin'
  },
  // 认证状态
  isAuthenticated: false,
  token: null,
  // 加载状态
  loading: false,
  // 错误信息
  error: null
}

const getters = {
  // 是否为管理员
  isAdmin: state => state.user.userType === 'admin',
  // 获取用户名
  username: state => state.user.username,
  // 获取用户类型
  userType: state => state.user.userType,
  // 获取跳转路径
  redirectPath: state => state.user.userType === 'admin' ? '/admin/dashboard' : '/',
  // 是否已登录
  isLoggedIn: state => state.isAuthenticated && state.token !== null
}

const mutations = {
  // 设置用户信息
  SET_USER(state, user) {
    state.user = { ...state.user, ...user }
    // 将用户类型持久化存储到localStorage
    localStorage.setItem('userType', state.user.userType)
    localStorage.setItem('username', state.user.username)
  },
  // 设置认证状态
  SET_AUTH(state, { isAuthenticated, token }) {
    state.isAuthenticated = isAuthenticated
    state.token = token
    // 将token持久化存储到localStorage
    if (token) {
      localStorage.setItem('token', token)
    } else {
      localStorage.removeItem('token')
      localStorage.removeItem('userType') // 登出时清除用户类型
      localStorage.removeItem('username')
    }
  },
  // 设置加载状态
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  // 设置错误信息
  SET_ERROR(state, error) {
    state.error = error
  },
  // 清除用户信息
  CLEAR_USER(state) {
    state.user = {
      id: null,
      username: '',
      userType: 'user',
    }
    state.isAuthenticated = false
    state.token = null
    // 从localStorage清除token
    localStorage.removeItem('token')
    localStorage.removeItem('userType')
    localStorage.removeItem('username')
  }
}

const actions = {
  // 用户登录
  async login({ commit }, { username, password }) {
    commit('SET_LOADING', true)
    commit('SET_ERROR', null)
    
    try {
      const response = await apiLogin(username, password)
      
      // 从正确路径获取token
      const token = response.data.data?.token 
      
      if (!token) {
        throw new Error('登录成功但未获取到token')
      }
      
      // 从正确路径获取用户信息
      const userData = response.data?.data 
      // 修复用户类型处理，确保正确设置为'admin'
      const isAdminUser = userData.user_type === 'admin' || userData.user_type === 'ADMIN' || userData.user_type === 1;
      const userInfo = {
        username: userData.username,
        userType: isAdminUser ? 'admin' : 'user',
        id: userData.id
      }
      
      commit('SET_USER', userInfo)
      commit('SET_AUTH', { isAuthenticated: true, token })
      
      // 修复重定向路径，确保与路由配置一致
      return {
        success: true,
        redirectPath: isAdminUser ? '/backindex' : '/',
        userType: userInfo.userType
      }
      
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
      // 在login action的成功处理部分添加
      // 用户登录成功后，通知购物车模块重新加载购物车数据
      this.dispatch('mall/onUserStatusChanged')
      
      // 同样在getUserInfo action的成功处理部分添加
      // 用户信息更新后，通知购物车模块重新加载购物车数据
      this.dispatch('mall/onUserStatusChanged')
      
      // 在logout action的finally块中添加
      // 用户登出后，清除购物车数据
      localStorage.removeItem('mallCart_guest')
      this.dispatch('mall/onUserStatusChanged')
    }
  },
  
  // 用户注册
  async register({ commit }, { username, password }) {
    commit('SET_LOADING', true)
    commit('SET_ERROR', null)
    
    try {
      const response = await apiRegister(username, password)
      
      // 注册成功后自动登录
      return await this.dispatch('user/login', { username, password })
      
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  // 获取用户信息
  async getUserInfo({ commit, state }) {
    try {
      const response = await getUserInfo()
      const userData = response.data?.data
      if (userData) {
        // 修复用户类型处理
        const isAdminUser = userData.user_type === 'admin' || userData.user_type === 'ADMIN' || userData.user_type === 1;
        commit('SET_USER', {
          username: userData.username,
          userType: isAdminUser ? 'admin' : 'user',
          id: userData.id,
        })
        commit('SET_AUTH', { isAuthenticated: true, token: state.token })
      }
      return response.data
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    }
  },
  
  // 用户登出
  async logout({ commit }) {
    try {
      await apiLogout()
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      commit('CLEAR_USER')
    }
  },
  
  // 清除错误信息
  clearError({ commit }) {
    commit('SET_ERROR', null)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}